package com.im.tcp.publisher;

import com.alibaba.fastjson.JSONObject;
import com.ecode.imecode.proto.Message;
import com.im.tcp.MQFactory;
import com.lld.im.common.constants.Constants;
import com.rabbitmq.client.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;

import java.nio.charset.StandardCharsets;

@Slf4j
public class MqChartMsgProduce {

    /**
     * 接收到客户端发送的消息 使用mq将消息发送到业务层
     * @param msg
     * @param command 标识消息
     */
    public static void sendMsg(Message msg,Integer command) {
        try {
            String exchangeName=Constants.RabbitConstants.Im2MessageService;
            Channel channel = MQFactory.getChannel("user");
            JSONObject jsonObject = (JSONObject)
                    JSONObject.toJSON(msg.getBodyData());
            jsonObject.put("command",command);
            jsonObject.put("appId",msg.getMessageHeader().getAppId());
            jsonObject.put("clientType",msg.getMessageHeader().getClientType());
            jsonObject.put("imei",msg.getImei());
            //对于群聊 都是以2开头的命令
            if(command.toString().startsWith("2")){
                exchangeName=Constants.RabbitConstants.Im2GroupService;
            }
            channel.basicPublish(exchangeName, "", null,
                    jsonObject.toJSONString().getBytes(StandardCharsets.UTF_8));
            log.info("tcp 发送消息成功！ msg=={}",jsonObject.toJSONString());
        } catch (Exception e) {
            log.error("tcp 消息发送失败！msg:{} e:{}",msg.toString(),e);
        }

    }

    /**
     * 初始化队列与交换机信息
     */
    public static void init(){
        try{
            String exchangeName=Constants.RabbitConstants.Im2MessageService;
            String queueName=Constants.RabbitConstants.Im2MessageService;
            Channel channel = MQFactory.getChannel("user");
            //声明队列 队列名 是否持久化 是否排他 是否自动删除 其它参数
            channel.queueDeclare(queueName, true, false, false, null);
            //交换机 队列 绑定
            channel.exchangeDeclare(exchangeName, ExchangeTypes.DIRECT,true,false,null);
            channel.queueBind(queueName,exchangeName,"");

            String exchangeGroupName=Constants.RabbitConstants.Im2GroupService;
            String queueGroupName=Constants.RabbitConstants.Im2GroupService;
            channel.exchangeDeclare(exchangeGroupName, ExchangeTypes.DIRECT,true,false,null);
            channel.queueDeclare(queueGroupName, true, false, false, null);
            channel.queueBind(queueGroupName,exchangeGroupName,"");
            log.error("MqChartMsgProduce 初始化交换机成功！");
        }catch (Exception e){
            log.error("MqChartMsgProduce 初始化交换机失败！e==={}",e.getMessage());
        }

    }
}
